package login;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取用户名和密码
        req.setCharacterEncoding("utf8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //2.判断用户或密码是否合法，此处要求用户为zhangsan和lisi，密码为123
        if(!(username.equals("zhangsan") || username.equals("lisi"))) {
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write("用户名或密码错误");
            return;
        }
        //判断密码是否正确
        if(!password.equals("123")) {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("密码或密码错误");
            return;
        }
        resp.getWriter().write("ok");

        //3.创建一个会话
        HttpSession session = req.getSession(true);

        //设置属性，使username中创建一个set-cookie和cookieId
        session.setAttribute("username",username);

        //4.重定向,跳转到index目录下
        resp.sendRedirect("index");
    }
}
